package com.liang.jiekou.service.impl;

import com.alibaba.fastjson.JSON;

import com.liang.jiekou.entity.*;
import com.liang.jiekou.entity.dto.MOCTGDto;
import com.liang.jiekou.mapper.CMSMQMapper;
import com.liang.jiekou.mapper.INVMBMapper;
import com.liang.jiekou.mapper.MOCTAMapper;
import com.liang.jiekou.mapper.RUKUMapper;
import com.liang.jiekou.service.HttpClientService;
import com.liang.jiekou.service.RUKUService;
import lombok.extern.slf4j.Slf4j;
import com.liang.jiekou.entity.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
//@Transactional
@Slf4j
public class RUKUServiceImpl implements RUKUService {



    @Resource
    CMSMQMapper cmsmqMapper;

    @Resource
    RUKUMapper rukuMapper;

    @Resource
    MOCTAMapper moctaMapper;


    @Resource
    INVMBMapper invmbMapper;


    @Resource
    HttpClientService httpClientService;


    @Override
    public RpcServiceResult<Map<String, Object>> insertAll(All all) throws UnknownHostException {
        BigDecimal zRKSL=new BigDecimal("0.0");
        BigDecimal zYSSL=new BigDecimal("0.0");
        BigDecimal zBFSL=new BigDecimal("0.0");
        BigDecimal zPHSL=new BigDecimal("0.0");
        BigDecimal zYTSL=new BigDecimal("0.0");
        BigDecimal zRKBZSL=new BigDecimal("0.0");
        BigDecimal zYSBZSL=new BigDecimal("0.0");
        BigDecimal zBFBZSL=new BigDecimal("0.0");
        BigDecimal zPHBZSL=new BigDecimal("0.0");
        BigDecimal zYTBZSL=new BigDecimal("0.0");

        MOCTF moctf = new MOCTF();

        moctf.setTF001("5810");
        Long dh = rukuMapper.getDH();
        List<MOCTGDto> moctgList = all.getMoctgList();
        List<MOCTG> moctgs = new ArrayList<>();

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 定义日期时间格式
        DateTimeFormatter formatter17 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        DateTimeFormatter formatter8 = DateTimeFormatter.ofPattern("yyyyMMdd");

        // 格式化时间
        String formattedTime17 = currentTime.format(formatter17);
        String formattedTime8 = currentTime.format(formatter8);

        Long time = Long.parseLong(currentTime.format(formatter8)+ "001");

        if (dh < time){
            dh = time;
        }else {
            dh++;
        }

        moctf.setTF002(""+dh);

        moctf.setCREATOR(all.getCreator());
        moctf.setCOMPANY("ttc");
        moctf.setCREATE_DATE(formattedTime17);
        moctf.setFLAG(new BigDecimal(2));

        moctf.setTF003(formattedTime8);
        for (int i = 0;i<moctgList.size();i++){
            MOCTGDto moctgDto = moctgList.get(i);
            String xuh = String.format("%04d", i + 1); // 使用String.format确保长度为4，并补全前导0
            MOCTG moctg = new MOCTG();
            moctg.setTG001("5810");
            moctg.setTG002(""+dh);
            moctg.setTG003(xuh);

            moctg.setTG014(moctgDto.getGddb());
            moctg.setTG015(moctgDto.getGddh());


            List<Map<String, Object>> listMOCTA = moctaMapper.selectMOCTA(moctg.getTG014(), moctg.getTG015());

                    for (Map<String, Object> mocta : listMOCTA) {
                        // 获取每个字段的值
                        moctg.setTG004((String) mocta.get("TA006"));
                        moctg.setTG007((String) mocta.get("TA007"));
                        //报废数量
                        BigDecimal ta018 = new BigDecimal(moctgDto.getBfbzsl());
                        moctg.setTG012(ta018);
                        moctg.setTG010((String) mocta.get("TA020"));
                        moctg.setTG005((String) mocta.get("TA034"));
                        moctg.setTG006((String) mocta.get("TA035"));
                        moctg.setTG024((String) mocta.get("TA044"));
                        //报废包装数量
                        BigDecimal bfbzsl = new BigDecimal(moctgDto.getBfbzsl());
                        moctg.setTG026(bfbzsl);
                        //包装单位
                        moctg.setTG029((String) mocta.get("TA048"));
                        moctg.setTG017((String) mocta.get("TA057"));
                        moctg.setTG031((String) mocta.get("TA058"));
                        //破坏数量
                        BigDecimal ta060 = new BigDecimal(moctgDto.getPhsl());
                        moctg.setTG032(ta060);
                        //破坏包装数量
                        BigDecimal ta061 = new BigDecimal(moctgDto.getPhbzsl());
                        moctg.setTG033(ta061);
                        moctg.setTGC01((String) mocta.get("TAC01"));
                        moctg.setTG021((String) mocta.get("TA083"));
                        //入库数量
                        BigDecimal TA015 = new BigDecimal(moctgDto.getRkls());
                        moctg.setTG011(TA015);
                        //验收数量
                        BigDecimal yssl = new BigDecimal(moctgDto.getYssl());
                        moctg.setTG013(yssl);
                        if (moctgDto.getJyzt().trim().isEmpty()) {
                            moctg.setTG016("2");
                        }else{
                            moctg.setTG016(moctgDto.getJyzt());
                        }
                        BigDecimal tg009 = new BigDecimal("1");
                        moctg.setTG009(tg009);
                        moctg.setTG022("N");
                        moctg.setTG020(moctgDto.getTG020());
                        //验退数量
                        BigDecimal ytsl = new BigDecimal(moctgDto.getYtsl());
                        moctg.setTG023(ytsl);
                        //入库包装数量
                        BigDecimal TA045 = new BigDecimal(moctgDto.getRkbzsl());
                        moctg.setTG025(TA045);
                        //验收包装数量
                        BigDecimal TA046 =  new BigDecimal(moctgDto.getYsbzsl());
                        moctg.setTG027(TA046);
                        //验退包装数量
                        BigDecimal ytbzsl = new BigDecimal(moctgDto.getYtbzsl());
                        moctg.setTG028(ytbzsl);
                        BigDecimal TG034 = new BigDecimal("0.0000");
                        moctg.setTG034(TG034);
                        moctg.setTG035("N");
                        moctg.setTG036("##########");
                        moctg.setTG037((String) mocta.get("TA007"));
                        moctg.setTG038(TA015);
                        moctg.setTG042(TG034);
                        moctg.setTG043(TG034);
                        moctg.setTG044(TG034);
                        moctg.setCREATE_DATE(formattedTime17);
                        moctg.setCOMPANY(moctf.getCOMPANY());
                        moctg.setCREATOR(moctf.getCREATOR());
                        BigDecimal flag = new BigDecimal("2");
                        moctg.setFLAG(flag);

                    }
                    //最大入库数量
                    String maxtg011 = moctaMapper.selectmax(moctg.getTG004(), moctg.getTG014(), moctg.getTG015());

                    if (moctg.getTG011().compareTo(new BigDecimal(maxtg011)) > 0) {
                        // moctg.getTG011() 大于 maxtg011
                        return RpcServiceResult.getFailureResult("-303", "输入的数量超过最大入库数量");
                    } else {
                        // 其他逻辑
                        moctg.setTG011(moctg.getTG011());
                    }
                   moctgs.add(moctg);
        }
        //1  SELECT * FROM CMSMB  只有编号1的工厂 暂时写死
        moctf.setTF004("1");

        moctf.setTF005(all.getTF005());

        moctf.setTF006("N");
        moctf.setTF007("N");
        BigDecimal num = new BigDecimal("0");
        moctf.setTF008(num);
        moctf.setTF009("N");
        moctf.setTF010("N");
        //工作中心只有一个 暂时写死
        moctf.setTF011("104");
        moctf.setTF012(formattedTime8);
        moctf.setTF013(all.getCreator());
        moctf.setTF014("N");
        moctf.setTF015(num);
        //部门只有一个暂时写死
        moctf.setTF016("1111");
        //总入库数量
        moctf.setTF023(zRKSL);
        //总验收数量
        moctf.setTF024(zYSSL);
        //总报废数量
        moctf.setTF025(zBFSL);
        //总破坏数量
        moctf.setTF026(zPHSL);
        //总验退数量
        moctf.setTF027(zYTSL);
        //总入库包装数量
        moctf.setTF028(zRKBZSL);
        //总验收包装数量
        moctf.setTF029(zYSBZSL);
        //总报废包装数量
        moctf.setTF030(zBFBZSL);
        //总破坏包装数量
        moctf.setTF031(zPHBZSL);
        //总验退包装数量
        moctf.setTF032(zYTBZSL);
        moctf.setUDF01(all.getUDF01());

        BigDecimal num1 = new BigDecimal("0.000000");
        moctf.setTF020(num1);
        moctf.setTF021(num1);
        moctf.setTF022(num1);

        rukuMapper.insertMOCTFDATA(moctf);

        for (MOCTG moctg : moctgs) {
            rukuMapper.insertMOCTGDATA(moctg);
        }

        ShenHe shenHe = new ShenHe();
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);
        shenHe.setCom("ttc");
        shenHe.setProgram("MOCI05");
        shenHe.setUser(all.getCreator());
        shenHe.setDb("5810");
        shenHe.setDh(""+dh);
        shenHe.setType("DO");
        shenHe.setRq(formattedDate);

        InetAddress localhost = InetAddress.getLocalHost();
        String ipAddress = localhost.getHostAddress();
        String url = "http://" + ipAddress + ":9000/api/yifei/audit";


        String jsonString = JSON.toJSONString(shenHe);
        String ans = null;
        try {
//            ShenHe anss=restTemplate.postForObject(url,shenHe,ShenHe.class);
            ans = httpClientService.postRequest(url, jsonString);
            System.out.println("ans"+ans.toString());

        }catch (Exception e){
            //System.out.println("出现异常请查看审批后台是否开启");
            log.info("出现异常请查看审批后台是否开启");
            System.out.println(e);
            return RpcServiceResult.getFailureResult("-10000", "出现异常请查看审批后台是否开启");
        }
        HttpResult httpResult = new HttpResult();
        if (ans == null)
        {
            System.out.println("出现异常请查看审批后台是否开启");
            return RpcServiceResult.getFailureResult("-10000", "出现异常请查看审批后台是否开启");
        }
        else {

            System.out.println("httpResult"+    httpResult);
            ans = ans.replace("\\r","");

            System.out.println("ans :"  + ans);
            httpResult = JSON.parseObject(ans,HttpResult.class);
//            System.out.println("httpResult: " + httpResult);

        }
        try {
            if (httpResult.getStatus().equals("失败")){
                rukuMapper.deleteMoctf(moctf.getTF001(),moctf.getTF002());
                for (MOCTG moctg : moctgs) {
                    rukuMapper.deleteMoctg(moctg.getTG001(), moctg.getTG002(),moctg.getTG003());
                }
                return RpcServiceResult.getFailureResult("-10001", "审核失败！\\n" + "原因：" + httpResult.getReason() + "\\n 详情：" + httpResult.getDetail());
            }
        }catch (NullPointerException e){
            rukuMapper.deleteMoctf(moctf.getTF001(),moctf.getTF002());
            for (MOCTG moctg : moctgs) {
                rukuMapper.deleteMoctg(moctg.getTG001(), moctg.getTG002(),moctg.getTG003());
            }
            return RpcServiceResult.getFailureResult("-10001", "请确认工单是否缺领或者超入");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        map.put("db","5810-"+dh);
        return RpcServiceResult.getSuccessResult(map);
    }



    @Override
    public RpcServiceResult<Map<String, Object>> delete(String TF001, String TF002) throws UnknownHostException {

        rukuMapper.deleteMOCTF(TF001, TF002);
        rukuMapper.deleteMOCTG(TF001, TF002);

        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        return RpcServiceResult.getSuccessResult(map);


    }

    @Override
    public Result update(String CREATOR, String TF001, String TF002) throws UnknownHostException {
        ShenHe shenHe = new ShenHe();
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);
        shenHe.setCom("ttc");
        shenHe.setProgram("MOCI05");
        shenHe.setUser(CREATOR);
        shenHe.setDb(TF001);
        shenHe.setDh(TF002);
        shenHe.setType("UNDO");
        shenHe.setRq(formattedDate);

        InetAddress localhost = InetAddress.getLocalHost();
        String ipAddress = localhost.getHostAddress();
        String url = "http://" + ipAddress + ":9000/api/yifei/audit";


        String jsonString = JSON.toJSONString(shenHe);


        String ans = null;
        try {
            ans = httpClientService.postRequest(url, jsonString);

        }catch (IOException e){
            //System.out.println("出现异常请查看审批后台是否开启");
            log.info("出现异常请查看审批后台是否开启");
            System.out.println(e);
            return Result.error("撤销审核的时候出现异常！");
        }
        HttpResult httpResult =  new HttpResult();
        if (ans == null)
            System.out.println("出现异常请查看审批后台是否开启");
        else {

            System.out.println(ans);
            ans = ans.replace("\\r","");

            System.out.println("ans :"  + ans);
            httpResult = JSON.parseObject(ans,HttpResult.class);
            System.out.println("httpResult: " + httpResult);
        }
        if (httpResult.getStatus().equals("失败"))
            return Result.error("撤销审核失败！\\n" + "原因：" + httpResult.getReason() + "\\n 详情：" + httpResult.getDetail());

        return Result.success();
    }


}